import axios from 'axios'
import UserService from '@/services/UserService'
import NavigationService from '@/services/NavigationService'

// // 创建axios实例
// const service = axios.create({
//   baseURL: 'http://10.43.26.219/api/v1', // api 的 base_url
//   timeout: 5000 // 请求超时时间
// })

// request拦截器
axios.interceptors.request.use(
  config => {
    if (UserService.getToken()) {
      config.headers['Authorization'] = UserService.getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
axios.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code !== 200) {
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        NavigationService.navigate('Login')
      }
      return Promise.reject('error')
    } else {
      return response
    }
  },
  error => {
    console.log('interceptors err' + error) // for debug
    return Promise.reject(error)
  }
)


// axios.defaults.baseURL = 'http://localhost/api/v1/'
axios.defaults.baseURL = 'http://10.43.26.219/api/v1/'
axios.defaults.timeout = 5000

export default class Http {

  static get(url) {
      return new Promise((resolve, reject) => {
          axios({
              method: 'GET',
              url: url,
              headers: {
                  'Content-Type': 'application/json', 

              }
          }).then( res=> {
              resolve(res.data)
          }).catch( err => {
              console.log("axios error",err)
              reject(err)
          })
      })
  }

  static post(url, payload) {
      console.log('post_url:', url)
      return new Promise((resolve, reject) => {
        axios({
          method: 'POST',
          url: url,
          data: payload,
          headers: {
              'Content-Type': 'application/json'    
          }
      }).then(res => {
          console.log('return:', res)
          resolve(res)
        }).catch(err => {
          console.log('error:', err)

          reject(err)
        })
      })
  }

}